<script setup lang="ts">
import { onMounted, ref } from 'vue'

const props = defineProps({
  color: {
    type: String,
    default: '#07f'
  }
})

// 避免重复id造成渲染错误
const id = Math.random().toString().replace('.', '')

let width = ref(0)
let height = ref(0)
let top = ref(0) // 可伸缩上部分
let right = ref(0) // 可伸缩右部分
let bottom = ref(0) // 可伸缩下部分
let left = ref(0) // 可伸缩左部分

let resizeObserver
let elRef = ref()

const resize = () => {
  if (elRef.value) {
    let style = getComputedStyle(elRef.value)
    width.value = parseInt(style.getPropertyValue('width'))
    height.value = parseInt(style.getPropertyValue('height'))
    top.value = Math.max(width.value - 50 - 10 - 4, 0)
    right.value = Math.max(height.value - 10 - 20 - 4, 0)
    bottom.value = Math.max(width.value - 10 - 50 - 10 - 4, 0)
    left.value = Math.max(height.value - 20 - 10 - 4, 0)
  }
}

onMounted(() => {
  resizeObserver = new window.ResizeObserver((entries) => resize())
  resizeObserver.observe(elRef.value)
})
</script>

<template>
  <svg ref="elRef" class="border" xmlns="http://www.w3.org/2000/svg">
    <defs>
      <filter :id="`f1-${id}`" x="-10%" y="-10%" width="120%" height="120%">
        <feComponentTransfer in="SourceAlpha">
          <!-- tableValues透明度映射，反向 -->
          <feFuncA type="table" tableValues="1 0" />
        </feComponentTransfer>
        <feGaussianBlur stdDeviation="8" />
        <feOffset dx="0" dy="0" result="offsetblur" />
        <feFlood :flood-color="color" result="color" />
        <feComposite in2="offsetblur" operator="in" />
        <feComposite in2="SourceAlpha" operator="in" />
        <!-- <feMerge>
          <feMergeNode in="SourceGraphic" />
          <feMergeNode></feMergeNode>
        </feMerge> -->
      </filter>
    </defs>
    <path :d="`M1 20 V10 L10 1 H50`" fill="none" stroke-width="2" :stroke="color"></path>
    <path
      :d="`M${width - 1} ${height - 20} v10 l-10 10 h-50`"
      fill="none"
      stroke-width="2"
      :stroke="color"
    ></path>
    <path :d="`M${width} 0 v10 l-10 -10`" :fill="color" stroke="none">
      <animate
        attributeName="opacity"
        values="0.5;1;0.5"
        dur="1s"
        repeatCount="indefinite"
      ></animate>
    </path>
    <path :d="`M0 ${height} v-10 l10 10`" :fill="color" stroke="none">
      <animate
        attributeName="opacity"
        begin="0.5s"
        values="0.5;1;0.5"
        dur="1s"
        repeatCount="indefinite"
      ></animate>
    </path>
    <path
      fill="#000"
      :filter="`url(#f1-${id})`"
      :d="`M50 1 h${top} L${width - 1} 14 v${right} v10 l-10 10 h-50 h-${bottom} l-12 -12 v-${left} v-10 l10 -10 z`"
    ></path>
  </svg>
</template>

<style scoped>
.border {
  pointer-events: none;
  width: 100%;
  height: 100%;
  position: absolute;
  inset: 0;
  z-index: 0;
}
</style>
